package com.controller;

import com.bean.Comment;
import com.bean.PaginationSupport;
import com.bean.Post;
import com.bean.User;
import com.db.CommentRepository;
import com.db.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private CommentRepository commentRepository;

    @RequestMapping(method = RequestMethod.GET)
    public String showUserPost(Model model){
        return "userPost";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String savePost(HttpServletRequest request, PostForm postForm, Model model, HttpSession session)
            throws Exception {

        request.setCharacterEncoding("UTF-8");
        User user = (User) session.getAttribute("user");

        String topic = new String(postForm.getTopic().getBytes("ISO-8859-1"),"utf-8");
        String content = new String(postForm.getContent().getBytes("ISO-8859-1"),"utf-8");
        /*System.out.println(topic);
        System.out.println(content);*/

        if(user != null){
            boolean topicIsNull = false;
            boolean contentIsNull = false;
            String errormessage = "错误：";
            if(topic.equals("") || topic == null){
                topicIsNull = true;
                errormessage += " 标题为空 ";
            }
            if(content.equals("") || content == null){
                contentIsNull = true;
                errormessage += " 内容为空 ";
            }
            if((!topicIsNull) && (!contentIsNull)){
                Post post = new Post(topic, content, user , new Date(),0,null,1);
                if(post != null){
                    postRepository.save(post);
                    return "redirect:/userHomePage";
                }else {
                    errormessage += " 数据库错误，未能插入 ";
                    session.setAttribute("savePostErrorMessage", errormessage);
                    return "redirect:/post";
                }
            }else{
                session.setAttribute("savePostErrorMessage", errormessage);
                return "redirect:/post";
            }
        }
        else
            return "redirect:/login";
    }

    /**
     * 查看单个帖子
     *
     * @param postID
     * @param model
     * @return
     */
    @RequestMapping(value = "/{postID}", method = RequestMethod.GET)
    public String post(@PathVariable("postID") int postID,
                       @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,HttpSession session, Model model) {

        Post post = postRepository.findOne(postID);
        post.addClickCount();
        postRepository.clickPost(post);
        session.setAttribute("postID",postID);
        model.addAttribute("post",post);
        model.addAttribute("comments",commentRepository.findCommentPage(post,pageNo,pageSize));
        return "post";
    }

    @RequestMapping(value = "/myPost", method = GET)
    public String viewMyPost(Model model, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                @RequestParam(value = "pageSize", defaultValue = "3") int pageSize,HttpSession session){

        User user = (User) session.getAttribute("user");
        try {
            model.addAttribute("paginationSupport", postRepository.findMyPostPage(user,pageNo, pageSize));
        } catch (Exception e) {

        }
        return "myPost";
    }

    @RequestMapping(value = "/postSearch", method = POST)
    public String viewPostSearch(Model model, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                 @RequestParam(value = "pageSize", defaultValue = "3") int pageSize,
                                 @RequestParam(value = "keyword" ,defaultValue = "")String keyword){
        try {
            keyword = new String(keyword.getBytes("ISO-8859-1"),"utf-8");
            model.addAttribute("paginationSupport", postRepository.findByKeyWord(keyword,pageNo,pageSize));
        } catch (Exception e) {

        }
        return "postSearch";
    }

    @RequestMapping(value = "modifyPost/{postID}", method = RequestMethod.GET)
    public String showEditPost(@PathVariable(value = "postID") int postID,
                               HttpSession session){
        Post post = postRepository.findOne(postID);
        session.setAttribute("userUpdatePost", post);
        return "modifyPost";
    }

    @RequestMapping(value = "modifyPost/{postID}", method = RequestMethod.POST)
    public String processEditPost(@RequestParam(value = "topic", defaultValue = "") String topic,
                                  @RequestParam(value = "content", defaultValue = "") String context,
                                  @PathVariable(value = "postID") int postID,
                                  HttpSession session) throws UnsupportedEncodingException, UnsupportedEncodingException {
        boolean topicisnull = false;
        boolean contextisnull = false;
        boolean posterIsSame = true;
        String errorMessage = "编辑失败： ";

        topic = new String(topic.getBytes("ISO-8859-1"),"utf-8");
        context = new String(context.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(topic);
        System.out.println(context);
        if((topic == null) || (topic.equals(""))){
            errorMessage += " 帖子主题为空 ";
            topicisnull = true;
        }
        if((context == null) || (context.equals(""))){
            errorMessage += " 帖子内容为空 ";
            contextisnull = true;
        }
        Post post = postRepository.findOne(postID);
        User user = (User)session.getAttribute("user");
        if(!post.getPoster().getUserName().equals(user.getUserName())){
            errorMessage += " 发帖和改帖用户不相同 ";
            posterIsSame = false;
        }
        if((!topicisnull) && (!contextisnull) && (posterIsSame)){

            postRepository.modifyMyPost(post,user,topic,context);
            return "redirect:/post/myPost";
        }else{
            session.setAttribute("userEditPostErrorMessage", errorMessage);
            return "redirect:/post/modifyPost/"+Integer.toString(postID);
        }
    }
}

